package com.gpb.common.utils;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期处理类
 * @author GuoPengBin
 * @dateTime Mar 31, 2014  10:50:42 AM
 */
public class DateUtils {
	private StringBuffer buffer = new StringBuffer();
	private static String ZERO = "0";
	private static DateUtils date;
	public static SimpleDateFormat FORMAT_YMD = new SimpleDateFormat("yyyyMMdd");
	public static SimpleDateFormat FORMAT_YMD_HMS1 = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
	public static SimpleDateFormat FORMAT_YMD_HMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public String getNowString() {
		Calendar calendar = getCalendar();
		buffer.delete(0, buffer.capacity());
		buffer.append(getYear(calendar));

		if (getMonth(calendar) < 10) {
			buffer.append(ZERO);
		}
		buffer.append(getMonth(calendar));

		if (getDate(calendar) < 10) {
			buffer.append(ZERO);
		}
		buffer.append(getDate(calendar));
		if (getHour(calendar) < 10) {
			buffer.append(ZERO);
		}
		buffer.append(getHour(calendar));
		if (getMinute(calendar) < 10) {
			buffer.append(ZERO);
		}
		buffer.append(getMinute(calendar));
		if (getSecond(calendar) < 10) {
			buffer.append(ZERO);
		}
		buffer.append(getSecond(calendar));
		return buffer.toString();
	}

	private static int getDateField(Date date,int field) {
		Calendar c = getCalendar();
		c.setTime(date);
		return c.get(field);
	}
	public static int getYearsBetweenDate(Date begin,Date end){
		int bYear=getDateField(begin,Calendar.YEAR);
		int eYear=getDateField(end,Calendar.YEAR);
		return eYear-bYear;
	}
	
	public static int getMonthsBetweenDate(Date begin,Date end){
		int bMonth=getDateField(begin,Calendar.MONTH);
		int eMonth=getDateField(end,Calendar.MONTH);
		return eMonth-bMonth;
	}
	public static int getWeeksBetweenDate(Date begin,Date end){
		int bWeek=getDateField(begin,Calendar.WEEK_OF_YEAR);
		int eWeek=getDateField(end,Calendar.WEEK_OF_YEAR);
		return eWeek-bWeek;
	}
	public static int getDaysBetweenDate(Date begin,Date end){
		int bDay=getDateField(begin,Calendar.DAY_OF_YEAR);
		int eDay=getDateField(end,Calendar.DAY_OF_YEAR);
		return eDay-bDay;
	}
	

	/**
	 * 获取date的amount月后的时间
	 * @param amount可正、可负
	 * @return
	 */
	public static Date getSpecficMonthDate(Date date,int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH, amount);
		return getStartDate(cal.getTime());
	}

	/**
	 * 获取date年后的amount年的第一天的开始时间
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficYearStart(Date date,int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.YEAR, amount);
		cal.set(Calendar.DAY_OF_YEAR, 1);
		return getStartDate(cal.getTime());
	}

	/**
	 * 获取date年后的amount年的最后一天的终止时间
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficYearEnd(Date date,int amount) {
		Date temp = getStartDate(getSpecficYearStart(date,amount + 1));
		Calendar cal = Calendar.getInstance();
		cal.setTime(temp);
		cal.add(Calendar.DAY_OF_YEAR, -1);
		return getFinallyDate(cal.getTime());
	}

	/**
	 * 获取date月后的amount月的第一天的开始时间
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficMonthStart(Date date,int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH, amount);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		return getStartDate(cal.getTime());
	}

	/**
	 * 获取当前自然月后的amount月的最后一天的终止时间
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficMonthEnd(Date date,int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(getSpecficMonthStart(date,amount + 1));
		cal.add(Calendar.DAY_OF_YEAR, -1);
		return getFinallyDate(cal.getTime());
	}

	/**
	 * 获取date周后的第amount周的开始时间（这里星期一为一周的开始）
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficWeekStart(Date date,int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.setFirstDayOfWeek(Calendar.MONDAY); /* 设置一周的第一天为星期一 */
		cal.add(Calendar.WEEK_OF_MONTH, amount);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		return getStartDate(cal.getTime());
	}

	/**
	 * 获取date周后的第amount周的最后时间（这里星期日为一周的最后一天）
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficWeekEnd(Date date,int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setFirstDayOfWeek(Calendar.MONDAY); /* 设置一周的第一天为星期一 */
		cal.add(Calendar.WEEK_OF_MONTH, amount);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		return getFinallyDate(cal.getTime());
	}
	
	public static Date getSpecficDateStart(Date date,int amount){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_YEAR, amount);
		return getStartDate(cal.getTime());
	}

	/**
	 * 得到指定日期的一天的的最后时刻23:59:59
	 * 
	 * @param date
	 * @return
	 */
	public static Date getFinallyDate(Date date) {
		String temp = FORMAT_YMD.format(date);
		temp += " 23:59:59";

		try {
			return FORMAT_YMD_HMS1.parse(temp);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 得到指定日期的一天的开始时刻00:00:00
	 * 
	 * @param date
	 * @return
	 */
	public static Date getStartDate(Date date) {
		String temp = FORMAT_YMD.format(date);
		temp += " 00:00:00";

		try {
			return FORMAT_YMD_HMS1.parse(temp);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 
	 * @param date 指定比较日期
	 * @param compareDate 
	 * @return
	 */
	public static boolean isInDate(Date date,Date compareDate){
		if(compareDate.after(getStartDate(date))&&compareDate.before(getFinallyDate(date))){
			return true;
		}else{
			return false;
		}
	}

	private int getYear(Calendar calendar) {
		return calendar.get(Calendar.YEAR);
	}

	private int getMonth(Calendar calendar) {
		return calendar.get(Calendar.MONDAY) + 1;
	}

	private int getDate(Calendar calendar) {
		return calendar.get(Calendar.DATE);
	}

	private int getHour(Calendar calendar) {
		return calendar.get(Calendar.HOUR_OF_DAY);
	}

	private int getMinute(Calendar calendar) {
		return calendar.get(Calendar.MINUTE);
	}

	private int getSecond(Calendar calendar) {
		return calendar.get(Calendar.SECOND);
	}

	private static Calendar getCalendar() {
		return Calendar.getInstance();
	}

	public static DateUtils getDateInstance() {
		if (date == null) {
			date = new DateUtils();
		}
		return date;
	}

	/**
	 * 将str转成java.util.Date str格式：2005-07-21或2005/07/21
	 * 
	 * @param strD
	 * @return
	 */
	public static Date strToDate(String strD) {
		int yyyy = Integer.parseInt(strD.substring(0, 4));
		int mm = Integer.parseInt(strD.substring(5, 7));
		int dd = Integer.parseInt(strD.substring(8, 10));
		Date da = new Date(yyyy - 1900, mm, dd);

		return da;
	}

	/**
	 * 输入:日期date\格式化模式format 输出:格式化后字符串
	 */
	public static String dateToString(Date date, String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);

		return formatter.format(date);
	}

	/**
	 * 日期比较
	 * 
	 * @param s1
	 * @param s2
	 * @return
	 */
	public static int dateDiff(String s1, String s2) {
		try {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
			ParsePosition pos = new ParsePosition(0);
			ParsePosition pos1 = new ParsePosition(0);
			Date dt1 = formatter.parse(s1, pos);
			Date dt2 = formatter.parse(s2, pos1);

			long l = dt1.getTime() - dt2.getTime();
			return (int) (l / 3600 / 1000 / 24);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static Date dateMinusDay(Date d, int day) {
		/*
		 * GregorianCalendar cal = new GregorianCalendar(); cal.setTime(d);
		 * cal.add(GregorianCalendar.DATE,day);
		 */
		d.setTime(d.getTime() - day * 3600 * 24 * 1000);
		return d;
	}

	/**
	 * 输入:excel的日期格式01/01/1990 输出:java.util.Date
	 * 功能说明:将excel的日期格式转换成java.util.Date格式
	 */
	public static Date xlsStrToDate(String strD) {// 01/01/1990 2005/07/21
		int yyyy = Integer.parseInt(strD.substring(6, 10));
		int dd = Integer.parseInt(strD.substring(0, 2));
		int mm = Integer.parseInt(strD.substring(3, 5)) - 1;
		Date da = new Date(yyyy - 1900, mm, dd);

		return da;
	}

	/**
	 * 将java.util.Date转换成java.sql.Date
	 * 
	 * @param d
	 * @return
	 */
	public static java.sql.Date utilToSqlDate(Date d) {
		if (d == null)
			return null;
		java.sql.Date dd = new java.sql.Date(d.getTime());

		return dd;
	}

	/**
	 * 将java.util.Date转换成java.sql.Time
	 * 
	 * @param d
	 * @return
	 */
	public static java.sql.Time utilToSqlTime(Date d) {
		if (d == null)
			return null;
		java.sql.Time dd = new java.sql.Time(d.getTime());

		return dd;
	}

	/**
	 * 将java.util.Date转换成java.sql.Timestamp
	 * 
	 * @param d
	 * @return
	 */
	public static java.sql.Timestamp utilToSqlTimestamp(java.util.Date d) {
		if (d == null)
			return null;
		java.sql.Timestamp dd = new java.sql.Timestamp(d.getTime());

		return dd;
	}

	/**
	 * 将strD转换成oracle的sql语句
	 * 
	 * @param strD
	 *            ：格式：YYYY-MM-DD 或YYYYMMDD
	 * @return
	 */
	public static String strToStrYMD(String strD) {
		String str = "";

		if (strD != null && strD.length() > 0)
			if (strD.equals("null"))
				str = "''";
			else
				str = "to_date('" + strD + "','YYYY-MM-DD')";

		return str;
	}

	/**
	 * 将strD转换成oracle的sql语句
	 * 
	 * @param strD
	 * @return
	 */
	public static String strToStrHMS(String strD) {
		String str = "";
		str = "to_date('" + strD + "','YYYY-MM-DD HH24:MI:SS')";

		return str;
	}

	/**
	 * 返回当前年份
	 * 
	 * @return
	 */
	public static String getCurrentYear() {
		int year;
		Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		return "" + year;
	}

	/**
	 * 返回当前月
	 * 
	 * @return
	 */
	public static String getCurrentMonth() {
		int month;
		Calendar c = Calendar.getInstance();
		month = c.get(Calendar.MONTH) + 1;
		if (month < 10)
			return "0" + month;
		else
			return "" + month;
	}

	/**
	 * 返回上个月
	 * 
	 * @return
	 */
	public static String getPreMonth() {
		int month;
		Calendar c = Calendar.getInstance();
		month = c.get(Calendar.MONTH) + 1;
		if (month < 10)
			return "0" + month;
		else
			return "" + month;
	}

	/**
	 * 返回当前日
	 * 
	 * @return
	 */
	public static String getCurrentDay() {
		int day;
		Calendar c = Calendar.getInstance();
		day = +c.get(Calendar.DAY_OF_MONTH);
		if (day < 10)
			return "0" + day;
		else
			return "" + day;
	}

	/**
	 * 返回上个年月
	 * 
	 * @return
	 */
	public static String getPrecYearMonth() {
		int month;
		Calendar c = Calendar.getInstance();
		month = c.get(Calendar.MONTH);
		if (month == 0) {
			return (c.get(Calendar.YEAR) - 1) + "12";
		}

		if (month < 10)
			return c.get(Calendar.YEAR) + "0" + month;
		else
			return c.get(Calendar.YEAR) + "" + month;
	}

	public static String strToday(int type) {
		String str = "";

		java.util.Date ud = new java.util.Date();
		java.sql.Date sd = new java.sql.Date(ud.getTime());

		if (type == 1) {
			str = sd.toString();
		} else {
			str = sd.toString().replaceAll("-", "");
		}
		return str;
	}

	/**
	 * 传入日期(20001011\2000-10-11等格式),分割出年月日,
	 * 
	 * @param strD
	 * @param type
	 * @return
	 */
	public static String getDateByType(String strD, int type) {
		String str = "";
		String yyyy = "", mm = "", dd = "";
		int div = 0;

		if (strD.length() == 10) {
			div = 1;
		}

		yyyy = strD.substring(0, 4);
		mm = strD.substring(4 + div, 6 + div);
		dd = strD.substring(6 + (div * 2), 8 + (div * 2));

		if (type == 1)
			str = yyyy;
		else if (type == 2)
			str = mm;
		else if (type == 3)
			str = dd;
		return str;
	}

	public static String yesterdayToStr(String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);

		Date tmpDate = new Date();
		tmpDate.setTime(new Date().getTime() - 86400000);
		return formatter.format(tmpDate);
	}

	public static String todayToStr(String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);

		return formatter.format(new Date());
	}

	public static String yesterdayToStr() {
		return yesterdayToStr("yyyy-MM-dd");
	}

	public static String todayToStr() {
		return todayToStr("yyyy-MM-dd");
	}

	/**
	 * 上个月的第一天,返回格式为format
	 * 
	 * @param format
	 * @return
	 */
	public static String prevMFirstDay(String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		SimpleDateFormat tmpformat = new SimpleDateFormat("yyyyMMdd");

		Date tmpDate = new Date();
		try {
			tmpDate
					.setTime(tmpformat.parse(
							tmpformat.format(tmpDate).substring(0, 6) + "01")
							.getTime() - 86400000);
			tmpDate
					.setTime(tmpformat.parse(
							tmpformat.format(tmpDate).substring(0, 6) + "01")
							.getTime());
			return formatter.format(tmpDate);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 返回上个月的最后一天,返回格式为format
	 * 
	 * @param format
	 * @return
	 */
	public static String prevMLastDay(String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		SimpleDateFormat tmpformat = new SimpleDateFormat("yyyyMMdd");

		// Date da=new Date(yyyy-1900,mm,dd);
		Date tmpDate = new Date();
		try {
			tmpDate
					.setTime(tmpformat.parse(
							tmpformat.format(tmpDate).substring(0, 6) + "01")
							.getTime() - 86400000);
			return formatter.format(tmpDate);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String prevMFirstDay() {
		return prevMFirstDay("yyyyMMdd");
	}

	public static String prevMLastDay() {
		return prevMLastDay("yyyyMMdd");
	}

	/**
	 * 返回当前月的第一天,返回格式为format
	 * 
	 * @param format
	 * @return
	 */
	public static String currMFirstDay(String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		SimpleDateFormat tmpformat = new SimpleDateFormat("yyyyMMdd");

		Date tmpDate = new Date();
		try {
			// tmpDate.setTime(tmpformat.parse(tmpformat.format(tmpDate).substring(0,6)+"01").getTime());
			tmpDate
					.setTime(tmpformat.parse(
							tmpformat.format(tmpDate).substring(0, 6) + "01")
							.getTime());
			return formatter.format(tmpDate);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 返回当前月的最后一天,返回格式为format
	 * 
	 * @param format
	 * @return
	 */
	public static String currMLastDay(String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		SimpleDateFormat tmpformat = new SimpleDateFormat("yyyyMMdd");

		Date tmpDate = new Date();
		try {
			tmpDate.setMonth(tmpDate.getMonth() + 1);
			tmpDate
					.setTime(tmpformat.parse(
							tmpformat.format(tmpDate).substring(0, 6) + "01")
							.getTime() - 86400000);
			return formatter.format(tmpDate);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 获得今天时间 2009-08-12
	 * 
	 * @return
	 */
	public static String getNowDay() {
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DATE);
		String sday="";
		String smonth="";
        if(day<10){
        	sday="0"+day;
        }else{
        	sday=""+day;
        }
        if(month<10){
        	smonth="0"+month;
        }else{
        	smonth=""+month;
        }
		return year + "-" + smonth + "-" + sday;
	}
	
    
	
	
	
	/**
	 * 获得几天前或者几天后的时间
	 * 
	 * @param day
	 * @return
	 */
	public static String getWeekDay(int day) {
		Calendar calen = Calendar.getInstance();
		calen.setTime(calen.getTime());
		calen.add(Calendar.DATE, day);
		int weekyear = calen.get(Calendar.YEAR);
		int weekmonth = calen.get(Calendar.MONTH) + 1;
		int weekday = calen.get(Calendar.DATE);
		return weekyear + "-" + weekmonth + "-" + weekday;
	}
    /**
     * 传入字符串时间，对此时间加减然后返回结果字符串时间
     * 2009-08-05
     * @param time
     * @param day
     * @return
     */
	public static String getOneDayTime(String time, int day) {

		Date date = getStringToData(time);

		Calendar calen = Calendar.getInstance();
		calen.setTime(date);
		calen.add(calen.DATE, day);
		System.out.println(date);
		int weekyear = calen.get(Calendar.YEAR);
		int weekmonth = calen.get(Calendar.MONTH) + 1;
		int weekday = calen.get(Calendar.DATE);
		return weekyear + "-" + weekmonth + "-" + weekday;
	}
	/**
	 * date转string 
	 * @param date
	 * @param ymd  格式
	 * @return
	 */
	public static String getDateToString(Date date,String ymd) {
		   SimpleDateFormat formatter = new SimpleDateFormat(ymd);
		   String dateString = formatter.format(date);
		   return dateString;
	}
	/**
	 * 字符串时间转DATA型时间
	 * 
	 * @param inVal
	 * @return
	 */
	public static Date getStringToData(String inVal) { 
		Date date = null; // 定义时间类型
		SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date = inputFormat.parse(inVal); // 将字符型转换成日期型
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}   

	/**
	 * 字符串时间转LONG型时间
	 * 
	 * @param inVal
	 * @return
	 */
	public static long fromDateStringToLong(String inVal) { 
		Date date = null; // 定义时间类型
		SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:ss");
		try {
			date = inputFormat.parse(inVal); // 将字符型转换成日期型
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date.getTime(); // 返回毫秒数
	}

	public static String currMFirstDay() {
		return currMFirstDay("yyyy-MM-dd");
	}

	public static String currMLastDay() {
		return currMLastDay("yyyy-MM-dd");
	}

	public static String currMFirstDayTime() {
		return currMFirstDay("yyyy-MM-dd") + " 00:00:00";
	}

	public static String currMLastDayTime() {
		return currMLastDay("yyyy-MM-dd") + " 23:59:59";
	}

	public static String currDLastTime() {
		return strToday(1) + " 23:59:59";
	}


	
	public static void main(String args[]){
		System.out.println(getSpecficDateStart(new Date(), 288));
		System.out.println(FORMAT_YMD_HMS1.format(getSpecficMonthDate(new Date(),-1)));
		

		/*
		 * Calendar c=Calendar.getInstance();
		 * System.out.println(c.getTime().getTime());
		 * 
		 * System.out.println("ddd"); System.out.println(c.getTime().getTime());
		 */
		System.out.println(currMLastDay());
	}
}
